# +_+ coding:utf-8 +_+

import threading
from utils import *

__author__ = 'cz'


const.MAX_KLINE = 1440


class KLinePool(object):
    _rlock = threading.RLock()
    _pool = list()
    _ma5 = list()
    _ma10 = list()

    def __init__(self):
        pass

    def append(self, kl):
        self._rlock.acquire()
        if len(self._pool) >= const.MAX_KLINE:
            self._pool.pop(0)
        self._pool.append(kl)
        if len(self._pool) < 5:
            self._ma5.append(0)
        else: 
            summa = 0   
            for item in self._pool[-5:]:
                summa = summa + item.end
            ma = summa/5.0
            self._ma5.append(ma)
        if len(self._pool) < 10:
            self._ma10.append(0)
        else:
            summa = 0
            for item in self._pool[-10:]:
                summa = summa + item.end
            ma = summa/10.0
            self._ma10.append(ma)
        self._rlock.release()
        
    def updatelastone(self, kl):
        self._rlock.acquire()
        if(self._pool[-1].ts == kl.ts):
            self._pool[-1] = kl
            if len(self._pool) < 5:
                self._ma5[-1] = 0
            else: 
                summa = 0   
                for item in self._pool[-5:]:
                    summa = summa + item.end
                ma = summa/5.0
                self._ma5[-1] = ma
            if len(self._pool) < 10:
                self._ma10[-1] = 0
            else:
                summa = 0
                for item in self._pool[-10:]:
                    summa = summa + item.end
                ma = summa/10.0
                self._ma10[-1] = ma
        else:
            print('not update, but append to')
            print('-1:klines:%s  ma5:%f   ma10:%f' %(self._pool[-1].to_string(),self._ma5[-1], self._ma10[-1]))
            print('-2:klines:%s  ma5:%f   ma10:%f' %(self._pool[-2].to_string(),self._ma5[-2], self._ma10[-2]))
            print('-3:klines:%s  ma5:%f   ma10:%f' %(self._pool[-3].to_string(),self._ma5[-3], self._ma10[-3]))
            self.append(kl)
        self._rlock.release()    
    def ma5(self):
        return self._ma5[-3:]
        
    def ma10(self):    
        return self._ma10[-3:]

    def getklines(self):
        return self._pool

    def getlatestkline(self):
        return self._pool[-1]
            
pool = KLinePool()


def append(kl):
    pool.append(kl)



